<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Googleplus {
	
	public function __construct() {
		
		$CI =& get_instance();
		$CI->config->load('googleplus');
				
		require APPPATH .'third_party/google-api-php-client/src/Google_Client.php';
		require APPPATH .'third_party/google-api-php-client/src/contrib/Google_PlusService.php';
		require APPPATH .'third_party/google-api-php-client/src/contrib/Google_Oauth2Service.php';
		
		$cache_path = $CI->config->item('cache_path');
		$GLOBALS['apiConfig']['ioFileCache_directory'] = ($cache_path == '') ? APPPATH .'cache/' : $cache_path;
		
		$this->client = new Google_Client();
		$this->client->setApplicationName($CI->config->item('application_name', 'googleplus'));
		$this->client->setClientId($CI->config->item('client_id', 'googleplus'));
		$this->client->setClientSecret($CI->config->item('client_secret', 'googleplus'));
		$this->client->setRedirectUri($CI->config->item('redirect_uri', 'googleplus'));
		$this->client->setDeveloperKey($CI->config->item('api_key', 'googleplus'));
		
		$this->oauth2 = new Google_Oauth2Service($this->client);
		$this->plus = new Google_PlusService($this->client);
		
	}
	
	public function __get($name) {
		
		if(isset($this->plus->$name)) {
			return $this->plus->$name;
		}
		return false;
		
	}
	
	public function __call($name, $arguments) {
		
		if(method_exists($this->plus, $name)) {
			return call_user_func(array($this->plus, $name), $arguments);
		}
		return false;
	}
	
	public function access($code){
		if($code != NULL){
			$this->client->authenticate();
			$_SESSION['access_token'] = $this->client->getAccessToken();
			$this->client->setAccessToken($_SESSION['access_token']);
		}else {
			throw new Exception(array('message' => 'Expected Authorization Code is missing'));
		}
	}
	
	public function getInfoUser(){
		if ($this->client->getAccessToken())
		{
			//$user = $this->oauth2->userinfo->get();
			$user = $this->plus->people->get('me');
			//$result = array_merge($user, $me);
			$_SESSION['access_token'] = $this->client->getAccessToken();
			
			return $user;
		}
		return null;
	}
	
	public function getProfile(){
		if ($this->client->getAccessToken())
		{
			//$user = $this->oauth2->userinfo->get();
			$me = $this->plus->people->get('me');
			$_SESSION['access_token'] = $this->client->getAccessToken();
			
			return $me;
		}
		return null;
	}
	
}
?>